﻿/// <reference path="../GeneratedArtifacts/viewModel.js" />

myapp.BrowseCustomers.Customer_postRender = function (element, contentItem) {

    // Set up a databind on screen.Customers.count
    contentItem.dataBind("screen.Customers.count", function (newValue) {
        // Update the total records display
        DisplayCustomerCount(contentItem.screen);
    });

    // Set up a databind on screen.Customers.selectedItem
    contentItem.dataBind("screen.Customers.selectedItem", function (newValue) {
        var SelectedItem = newValue;
        // do we have a selected Customer?
        if (SelectedItem != undefined && SelectedItem != null) {
            // Update the display to show the last selected Customer
            var strDisplayText = "SelectedItem CustomerName: " + SelectedItem.CustomerName;
            contentItem.screen.details.displayName = strDisplayText;
        }
    });
};

myapp.BrowseCustomers.CallGetCustomers_execute = function (screen) {
    // Call getCustomers
    screen.getCustomers().then(function (result) {
        var index = result.data.length; // gets length of the full Customer array
        // The last Customer found in the 
        // collection will be 
        // set to LatestLoadedCustomer
        screen.LatestLoadedCustomer = result.data[index - 1]; // compensate for 0-based index

        // Show the Popup to display 
        // LatestLoadedCustomer
        screen.showPopup("LatestCustomer");
    });
};

myapp.BrowseCustomers.GetMoreRecords_execute = function (screen) {
    if (screen.Customers.canLoadMore) {
        // We can load more records -- load them
        screen.Customers.loadMore().then(function (result) {
            var index = result.items.length; // gets length of the full Customer array
            // The last Customer found in the 
            // collection will be 
            // set to LatestLoadedCustomer
            screen.LatestLoadedCustomer = result.items[index - 1]; // compensate for 0-based index

            // Show the Popup to display 
            // LatestLoadedCustomer
            screen.showPopup("LatestCustomer");

            // Update the total records display
            DisplayCustomerCount(screen);
        });
    }
};

// Utility
function DisplayCustomerCount(screen) {
    // If there is a Customer collection
    // display the current count
    if (screen.Customers != undefined && screen.Customers != null) {
        var strDisplayText = "Loaded Customers: " + screen.Customers.count;
        screen.details.displayName = strDisplayText;
    }
}
